package com.jackeysun.common

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.RecyclerView
import java.lang.NullPointerException

abstract class AbsAdapter<T : IData<AbsViewHolder>>(private val layoutId: Int = -1) :
    RecyclerView.Adapter<AbsViewHolder>() {

    lateinit var data: List<T>
    val layoutIds: MutableMap<Int, Int> by lazy { mutableMapOf() }

    init {
        if (layoutId != -1){
            layoutIds[0] = layoutId
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AbsViewHolder {
        return createHolder(parent, viewType)
    }

    override fun onBindViewHolder(holder: AbsViewHolder, position: Int) {
        data[position].bind(holder)
    }

    override fun getItemCount(): Int = try {
        data.size
    } catch (e: Exception) {
        0
    }

    override fun getItemViewType(position: Int): Int {
        return data[position].getType()
    }

    private fun createHolder(parent: ViewGroup, viewType: Int): AbsViewHolder {
        return AbsViewHolder(
            parent.getItemView(
                layoutIds[viewType] ?: throw NullPointerException("需要一个布局")
            )
        )
    }

    private fun ViewGroup.getItemView(@LayoutRes layoutResId: Int): View {
        return LayoutInflater.from(this.context).inflate(layoutResId, this, false)
    }
}